<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { shipmentsApi } from '../api/shipments'

type Product = { name: string; price: number }
type Item = { quantity: number; price: number; product: Product }
type Order = { id: number; customer: string; items: Item[] }
type Shipment = { shipment_date?: string; status?: string }

const route = useRoute()
const data = ref<{ order?: Order; shipment?: Shipment }>({})

async function load() {
  try {
    const orderId = route.params.orderId
    const res = await shipmentsApi.getDeliveryNote(Number(orderId))
    data.value = res.data
  } catch (e: any) {
    console.error('加载送货单失败:', e)
  }
}

function printPage() { window.print() }

onMounted(load)
</script>

<template>
  <div class="paper">
    <header>
      <div class="company">
        <h1>某某公司 送货单</h1>
        <div>地址：___________ 电话：___________</div>
      </div>
      <div class="meta">
        <div>订单号：{{ data.order?.id }}</div>
        <div>客户：{{ data.order?.customer }}</div>
        <div>发货日期：{{ data.shipment?.shipment_date || '-' }}</div>
        <div>状态：{{ data.shipment?.status || '-' }}</div>
      </div>
    </header>
    <table>
      <thead>
        <tr>
          <th>商品</th>
          <th>单价</th>
          <th>数量</th>
          <th>金额</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(it, idx) in data.order?.items || []" :key="idx">
          <td>{{ it.product?.name }}</td>
          <td>¥ {{ (it.price || 0).toFixed(2) }}</td>
          <td>{{ it.quantity }}</td>
          <td>¥ {{ ((it.price || 0) * (it.quantity || 0)).toFixed(2) }}</td>
        </tr>
      </tbody>
    </table>
    <footer>
      <div class="sign">
        <div>制单：________</div>
        <div>发货：________</div>
        <div>签收：________</div>
      </div>
      <div class="ops">
        <button @click="printPage">打印</button>
      </div>
    </footer>
  </div>
  
</template>

<style scoped>
.paper { max-width: 900px; margin: 0 auto; padding: 16px; background: #fff; color: #000; }
header { margin-bottom: 12px; display: flex; justify-content: space-between; align-items: flex-end; }
.company h1 { margin: 0; }
.meta { text-align: right; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; }
footer { display: flex; justify-content: space-between; margin-top: 16px; }
.sign > div { margin-right: 24px; display: inline-block; }
@media print { button { display: none; } }
</style>